package com.huadao.cart_ccs.base;

import android.accounts.NetworkErrorException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huadao.cart_ccs.data.source.http.RetrofitHelper.DEFAULT_TIME;

public class BaseHttpModel extends BaseModel {
    public <T> void toSubscribe(Observable<T> observable, Observer<T> observer) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .timeout(DEFAULT_TIME, TimeUnit.SECONDS)
                .retryWhen(new Function<Observable<Throwable>, ObservableSource<?>>() {
                    private int retryCount;
                    @Override
                    public ObservableSource<?> apply(Observable<Throwable> throwableObservable) throws Exception {
                        return throwableObservable.flatMap(new Function<Throwable, ObservableSource<?>>() {
                            @Override
                            public ObservableSource<?> apply(Throwable throwable) throws Exception {
                                if ((throwable instanceof NetworkErrorException || throwable instanceof ConnectException || throwable instanceof SocketTimeoutException || throwable instanceof TimeoutException) && retryCount < 3) {
                                    retryCount++;
                                    return Observable.timer(2000, TimeUnit.MILLISECONDS);
                                }
                                return Observable.error(throwable);
                            }
                        });
                    }
                })
                .subscribe(observer);
    }
}
